<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :lg="24" :xs="24" class="mb-[12px]">
        <el-card style="min-width: 480px;margin-bottom: 18px;">
          <template #header>
            <div class="card-header">
              <span>问题发起</span>
            </div>
          </template>

          <el-form
            ref="problemFormRef"
            :model="formData"
            label-width="120px"
            disabled="true"
          >
            <div class="form-flex">
              <el-form-item label="问题标题" prop="title" class="form-item">
                <el-input v-model="formData.title" />
              </el-form-item>
            </div>
            <div class="form-flex">
              <el-form-item label="问题来源" prop="source" class="form-item">
                <el-select v-model="formData.source">
                  <el-option label="内部问题" value="1" />
                  <el-option label="外部问题" value="2" />
                </el-select>
              </el-form-item>
              <el-form-item label="问题等级" prop="level" class="form-item">
                <el-select v-model="formData.level">
                  <el-option label="致命" value="1" />
                  <el-option label="严重" value="2" />
                  <el-option label="一般" value="3" />
                  <el-option label="提示" value="4" />
                </el-select>
              </el-form-item>
            </div>
            <div class="form-flex">
              <el-form-item label="问题描述" prop="description">
                <div style="border: 1px solid #ccc; margin-top: 10px;">
                  <Toolbar
                    style="border-bottom: 1px solid #ccc"
                    :editor="editorRef"
                    :mode="mode"
                  />
                  <Editor
                    style="height: 200px; overflow-y: hidden;width: 1000px;"
                    :mode="mode"
                    :defaultConfig="editorConfig"
                    @onCreated="handleCreated"
                  />
                </div>
              </el-form-item>
            </div>
            <div class="form-flex">
              <el-form-item label="期望解决时间" prop="expectTime" class="form-item">
                <el-date-picker
                  v-model="formData.expectTime"
                  type="datetime"
                />
              </el-form-item>
              <el-form-item label="责任人" prop="assigner" class="form-item">
                <el-select v-model="formData.assigner" filterable>
                  <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :value="item.userId"
                  :label="item.nickName"/>
                </el-select>
              </el-form-item>
            </div>
            <div class="form-flex">
              <el-form-item label="提出人" prop="creator" class="form-item">
                <el-select v-model="formData.creator" :disabled="true">
                  <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :value="item.userId"
                  :label="item.nickName"/>
                </el-select>
              </el-form-item>
              <el-form-item label="提出时间" prop="createTime" class="form-item">
                <el-date-picker
                  v-model="formData.createTime"
                  type="datetime"
                  :disabled="true"
                />
              </el-form-item>
            </div>
            <div class="form-flex">
              <el-form-item label="附件" prop="attachments" class="form-item">
                <el-upload
                  v-model:file-list="fileList"
                  class="upload-demo"
                  action="/api/bus/upload/uploadFiles"
                  multiple
                  :on-remove="handleRemove"
                  :limit="3"
                  :on-success="handleFileSuccess"
                  :before-upload="beforeFileUpload"
                  :on-preview="handleFilePreview"
                >
                  <el-button type="primary">上传附件</el-button>

                </el-upload>
              </el-form-item>
            </div>
          </el-form>
        </el-card>

        <el-card style="min-width: 480px;margin-bottom: 18px;">
          <template #header>
            <div class="card-header">
              <span>问题处理</span>
            </div>
          </template>

          <el-form
            ref="dealFormRef"
            :model="formData"
            :rules="rules"
            label-width="100px"
          >
            <el-form-item label="解决方案" prop="resolveType">
              <el-select v-model="formData.resolveType">
                <el-option label="设计如此" value="1" />
                <el-option label="重复问题" value="2" />
                <el-option label="已解决" value="3" />
                <el-option label="外部原因" value="4" />
                <el-option label="无法重现" value="5" />
                <el-option label="延期处理" value="6" />
                <el-option label="不予解决" value="7" />
              </el-select>
            </el-form-item>

            <el-form-item label="备注" prop="resolveRemark">
              <el-input v-model="formData.resolveRemark" :rows="3" type="textarea" />
            </el-form-item>
          </el-form>

          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="handleSubmit">提 交</el-button>
              <el-button type="primary" @click="handleTransfer">转 办</el-button>
            </div>
          </template>
        </el-card>

        <!-- 转办弹窗 -->
        <el-dialog
          v-model="transferDialogVisible"
          title="选择转办人员"
          width="500"
          align-center
        >
          <el-select v-model="transferUser" placeholder="请选择转办人员" filterable>
            <el-option
              v-for="item in userList"
              :key="item.userId"
              :value="item.userId"
              :label="item.nickName"/>
          </el-select>

          <template #footer>
            <div class="dialog-footer">
              <el-button @click="transferDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="handleSelectUser">
                确 定
              </el-button>
            </div>
          </template>
        </el-dialog>

        <flowHistory :flowId="route.query.flowId" :workId="route.query.workId" />
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ProblemDeal",
  inheritAttrs: false,
});

import flowHistory from '../../work/backlog/components/flowHistory.vue';
import ProjectAPI, { ProjectProblemData } from "@/api/project";
import UserAPI from "@/api/user";
import WorkAPI from "@/api/work";
import router from "@/router";
import { useTagsViewStore, useSettingsStore } from "@/store";
import {Editor, Toolbar} from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css'; // 引入 css

const route = useRoute();
const tagsViewStore = useTagsViewStore();
const settingsStore = useSettingsStore();
const problemFormRef = ref(ElForm);

// 人员选择框
const userList = ref([]);

// 项目表单
const formData = reactive<ProjectProblemData>({
  workId: 0,
  processId: 0,
  workNodes: '',
});
const rules = reactive({
  resolveType: [{ required: true, message: "请选择解决方案", trigger: "blur" }],
  resolveRemark: [{ required: true, message: "请输入备注", trigger: "blur" },{ min: 1, max: 100, message: '输入长度在 1 到 100 个字符', trigger: 'blur' }],
});

// 富文本
const editorRef = shallowRef()  // 编辑器实例，必须用 shallowRef
const mode = 'default'
const editorConfig = {MENU_CONF: {}}
editorConfig.readOnly = true
// 组件销毁时，也及时销毁编辑器，否则可能会造成内存泄漏
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
// 记录 editor 实例，重要！
const handleCreated = (editor) => {
  editorRef.value = editor
  editorRef.value.disable()  //禁用
}

const fileList = ref<UploadUserFile[]>([])
const handleFileSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  formData.attachments = response.data
}
const beforeFileUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 50) {
    ElMessage.error('文件大小不能超过50MB!')
    return false
  }
  return true
}
const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  // console.log(file, uploadFiles)
}

// 问题处理相关
const dealFormRef = ref(ElForm);
const loading = ref(false);

/** 问题处理 */
const handleSubmit = () => {
  dealFormRef.value.validate((valid: any) => {
    if (valid) {
      formData.workId = route.query.workId;
      formData.processId = route.query.processId;
      loading.value = true;
      ProjectAPI.problemDeal(formData)
          .then((data) => {
            ElMessage.success(data.msg);
            ElMessage.success(data.data);
            if (settingsStore.tagsView){
              tagsViewStore.closeCurrentView();
            }
            router.push({ path: '/projectList/view' });
          })
          .finally(() => (loading.value = false));
    }
  });
}

function handleFilePreview(file) {
  const fileUrl = file.url
  const a = document.createElement('a')
  a.href = fileUrl
  a.download = file.name
  a.style.display = 'none'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

// 转办
const transferDialogVisible = ref(false);
const transferUser = ref(null);
const handleTransfer = () => {
  transferDialogVisible.value = true;
}
const handleSelectUser = () => {
  if (!transferUser.value){
    ElMessage.warning("请选择转办人员");
    return;
  }
  loading.value = true;
  WorkAPI.workTransfer(formData.processId, transferUser.value)
      .then(({data}) => {
        ElMessage.success("转办成功");
        // 跳转到待办工作
        if (settingsStore.tagsView){
          tagsViewStore.closeCurrentView();
        }
        router.push({ path: '/backlog/view'});
      })
      .finally(() => (loading.value = false));
}

onMounted(() => {
  if (route.query.workId){
    ProjectAPI.getProblemByWorkId(route.query.workId).then(({data}) => {
      if (data){
        formData.id = data.id;
        formData.title = data.title;
        formData.source = data.source.toString();
        formData.level = data.level.toString();
        formData.description = data.description;
        editorRef.value.setHtml(data.description)
        formData.expectTime = data.expectTime;
        formData.status = data.status;
        formData.creator = data.creator;
        formData.createTime = data.createTime;
        formData.assigner = data.assigner;
        formData.attachments = data.attachments;
        if (formData.attachments){
          let files = JSON.parse(formData.attachments);
          for(let i = 0; i < files.length; i++){
            fileList.value.push({name: files[i]["name"], url: files[i]["url"]});
          }
        }
      }
    })
  }

  if (route.query.processId) {
    formData.processId = route.query.processId;
  }

  // 获取用户列表
  UserAPI.getUserList()
    .then(({data}) => {
      userList.value = data;
      formData.creator = parseInt(sessionStorage.getItem('userId'));
  })
});
</script>

<style type="text/css">
  .form-flex {
    display: flex;
    gap: 10px; /* 间距 */
    margin-bottom: 18px;
  }
  .form-item {
    flex: 1; /* 使所有表单项平均分配空间 */
    margin: 0; /* 移除默认的 margin */
  }
</style>

